package com.tg.app.service;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.JobIntentService;

import com.tange.core.backend.service.response.RxResponse;
import com.tange.feature.device.query.DeviceQuery;
import com.tg.app.bean.FirmwareUpgrade;
import com.tg.app.bean.FirmwareUpgrade_;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceItem;

import java.util.List;

import io.objectbox.Box;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Describe:
 * Created by Rance Rang on 2019-06-03.
 * <p>
 * Copyright (c) Tange.Inc All rights reserved.
 */
public class UpgradeService extends JobIntentService {

    private static final String TAG = "UpgradeService";

    // 最多等待3分钟
    private static final long MAX_WAITING_TIME = 180;

    // 该时间段内，回调假进度
    private static final long MID_WAITING_TIME = 90;

    public  static  final  int    UPGRADE_SUCCESS =  10;//升级成功
    public  static  final  int    UPGRADE_FAILURE =  11;//升级失败
    private static final int JOB_ID = 1000;

    @Override
    public void onCreate() {
        super.onCreate();

    }

    /**
     *  假升级进度
     */
    private synchronized void upgrade(){
       Box<FirmwareUpgrade> box  =ObjectBoxUtil.getFirmwareUpgrade();
       if (box==null)return;
        List<FirmwareUpgrade> upgradeList =box.query().build().find();
        if (upgradeList==null||upgradeList.size()==0){
            TGLog.i(TAG, "[upgrade] nothing to be upgrade.");
        }else {
            long curTms =  System.currentTimeMillis();
            for (FirmwareUpgrade upgrade :upgradeList){
                 curTms = (curTms-upgrade.created_at)/1000;

                TGLog.i(TAG, "[upgrade] handle deviceUuid = " + upgrade.deviceUuid);

                TGLog.i(TAG, "[upgrade] time past = " + curTms);

                 //进度90%以下，每秒加一
                if (upgrade.progress < MID_WAITING_TIME){
                    upgrade.progress += 1;
                    TGLog.i(TAG, "[upgrade] post fake progress " + upgrade.progress);
                } else if (curTms < MAX_WAITING_TIME) {

                    // 90 - 180s 之间， 每 5s，查询一次后台的设备版本号

                    if (curTms % 5 == 0) {
                        TGLog.i(TAG, "[upgrade] upgrade.realVersion_no = " + upgrade.realVersion_no);
                        TGLog.i(TAG, "[upgrade] upgrade.targetVersion_no = " + upgrade.targetVersion_no);

                        if (!TextUtils.isEmpty(upgrade.targetVersion_no) && upgrade.targetVersion_no.equals(upgrade.realVersion_no)) {
                            upgrade.status = UPGRADE_SUCCESS;
                            upgrade.progress = 100;
                            TGLog.i(TAG, "[upgrade] upgrade ok because version match !");
                        } else {
                            TGLog.i(TAG, "[upgrade] ask server for device version !");
                            requestDeviceVersionInfo(upgrade.deviceUuid);
                        }
                    }
                } else if (curTms > MAX_WAITING_TIME && upgrade.status != UPGRADE_SUCCESS){ //3分钟没有收到升级成功消息，显示失败
                    TGLog.i(TAG, "[upgrade] failed because out-of-time !");
                    upgrade.status = UPGRADE_FAILURE;
                    requestDeviceVersionInfo(upgrade.deviceUuid);
                }

            }
            box.put(upgradeList);
        }
    }

    private synchronized void updateDeviceVersionToLocal(String uuid, String versionNo){
        Box<FirmwareUpgrade> box  =ObjectBoxUtil.getFirmwareUpgrade();
        if (box==null)return;
        FirmwareUpgrade firmwareUpgrade =box.query().equal(FirmwareUpgrade_.deviceUuid, uuid).build().findFirst();
        if (firmwareUpgrade==null){
            TGLog.i(TAG, "[updateDeviceVersionToLocal] nothing to be update.");
        }else {
            TGLog.i(TAG, "[updateDeviceVersionToLocal] handle deviceId = " + firmwareUpgrade.deviceId);
            firmwareUpgrade.realVersion_no = versionNo;
            TGLog.i(TAG, "[updateDeviceVersionToLocal] new realVersion_no = " + firmwareUpgrade.realVersion_no);
            box.put(firmwareUpgrade);
        }
    }

    public void requestDeviceVersionInfo(String uuid){
        TGLog.i(TAG, "[requestDeviceVersionInfo] uuid = " + uuid);
        if (TextUtils.isEmpty(uuid)) {
            return;
        }
        DeviceQuery.INSTANCE.querySingleFull(uuid).observeOn(Schedulers.io()).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<RxResponse<DeviceItem>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(RxResponse<DeviceItem> deviceItemRxResponse) {
                if (deviceItemRxResponse != null && deviceItemRxResponse.isSuccess && deviceItemRxResponse.content != null) {
                    TGLog.i(TAG, "[requestDeviceVersionInfo] onSuccess current_version = " + deviceItemRxResponse.content.current_version);
                    TGLog.i(TAG, "[requestDeviceVersionInfo] onSuccess current_version_code = " + deviceItemRxResponse.content.current_version_code);

                    updateDeviceVersionToLocal(uuid, deviceItemRxResponse.content.current_version);
                }
            }

            @Override
            public void onError(Throwable e) {
                TGLog.i(TAG, "[requestDeviceVersionInfo][onError] " + Log.getStackTraceString(e));
            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, UpgradeService.class, JOB_ID, work);
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        upgrade();
    }


}
